import axios from 'axios';
import {showFailToast} from "vant";
import router from "../modules/router.js";
import {getToken, removeToken} from "@/utils/auth.js";
import {clearLocalStorage} from "@/utils/localStorage.js";

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        config.headers['X-Access-Token'] = getToken() || ''
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code != 200){
            showFailToast(res.message || 'service error')
            Promise.reject(res)
        }else {
            return res;
        }

    },
    error => {
        console.log('er',error)
        const e = error.response.data
        const status = error.response.status
        showFailToast(e.message || 'service error')
        if (status === 401){
            clearLocalStorage()
            router.push('/login')
        }
        return Promise.reject(e);
    }
);

export default service;
